﻿using System.Windows;
using System.Windows.Input;
using System;
using Ops.Mpc.Events;

namespace Ops.Mpc.Wcf
{
    public class CancelContext : IDisposable 
    {

        public bool Cancelled
        {
            get;
            private set; 
        }

        private ErrorHandler ErrorHandler
        {
            get;
            set;
        }

        public CancelContext(ErrorHandler errorHandler)
        {
            this.ErrorHandler = errorHandler;
            Application.Current.RootVisual.KeyDown += new KeyEventHandler(OnKeyDown);
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Cancelled = true; 
                e.Handled = true;

                if (this.ErrorHandler != null)
                    this.ErrorHandler("Operation Canceled", new OperationCancelledException("Operation Canceled"));
            }
        }

        void IDisposable.Dispose()
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.RootVisual.KeyDown -= new KeyEventHandler(OnKeyDown);
            });
        }

    }
}
